package com.example.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.utils.HttpUtils;
import com.example.gulimall.member.dao.MemberLevelDao;
import com.example.gulimall.member.entity.MemberLevelEntity;
import com.example.gulimall.member.exception.PhoneException;
import com.example.gulimall.member.exception.UsernameException;
import com.example.gulimall.member.vo.MemberUserLoginVo;
import com.example.gulimall.member.vo.MemberUserRegisterVo;
import com.example.gulimall.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.awt.image.BandCombineOp;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.member.dao.MemberDao;
import com.example.gulimall.member.entity.MemberEntity;
import com.example.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册业务处理操作
     * @author GuLin
     * @date 23:01 2021/6/29
     * @param registerVo
     * @return void
     **/
    @Override
    public void register(MemberUserRegisterVo registerVo) {
        MemberEntity entity = new MemberEntity();
        //设置等级
        // 设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());

        // 检查手机号 用户名是否唯一
        checkPhone(registerVo.getPhone());
        checkUserName(registerVo.getUserName());

        entity.setUsername(registerVo.getUserName());
        //密码盐+加密存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(bCryptPasswordEncoder.encode(registerVo.getPassword()));
        entity.setNickname(registerVo.getUserName());
        entity.setMobile(registerVo.getPhone());
//        entity.setEmail("");
//        entity.setHeader();
//        entity.setGender();
//        entity.setBirth();
//        entity.setCity();
//        entity.setJob();
        entity.setSign("这个家伙很懒，还没有签名");
        entity.setSourceType(1);
        entity.setIntegration(100);
        entity.setGrowth(100);
        entity.setStatus(0);
        entity.setCreateTime(new Date());
//        entity.setSocialUid();
//        entity.setAccessToken();
//        entity.setExpiresIn();
        this.baseMapper.insert(entity);
    }

    /**
     * 登陆业务处理
     * @author GuLin
     * @date 23:36 2021/6/29
     * @param loginVo
     * @return com.example.gulimall.member.entity.MemberEntity
     **/
    @Override
    public MemberEntity login(MemberUserLoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        //以用户名或电话号登录的进行查询
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if(null != entity){
           BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean flag = bCryptPasswordEncoder.matches(loginVo.getPassword(), entity.getPassword());
            if(flag) {
                entity.setPassword("");//返回给前台置空密码信息
                return entity;
            }
        }
        return null;
    }

    /**
     * 微博登陆
     * @author GuLin
     * @date 9:27 2021/6/30
     * @param socialUser
     * @return com.example.gulimall.member.entity.MemberEntity
     **/
    @Override
    public MemberEntity oauthLogin(SocialUserVo socialUser) throws Exception{
        //具有登录和注册逻辑
        String uid = socialUser.getUid();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(String.valueOf(socialUser.getExpires_in()));
            baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(socialUser.getExpires_in()));
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称、性别等）
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");

                register.setNickname(name);
                register.setGender("m".equals(gender) ? 1 : 0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(socialUser.getUid());
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

                //把用户信息插入到数据库中
                baseMapper.insert(register);
            }
            return register;
        }
    }

    private void checkUserName(String userName) {
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    private void checkPhone(String phone) {
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (phoneCount > 0) {
            throw new PhoneException();
        }

    }

}